import os
import chardet


def detect_file_encoding(file_path):

    with open(file_path, 'rb') as f:
        raw_data = f.read(1024)
    result = chardet.detect(raw_data)
    return result['encoding']


def open_file(file_path):

    if not os.path.exists(file_path):
        raise FileNotFoundError(f"文件 '{file_path}' 不存在")

    try:
        encoding = detect_file_encoding(file_path)
        with open(file_path, 'r', encoding=encoding) as f:
            content = f.read()
        return content
    except UnicodeDecodeError:

        encodings = ['utf-8', 'gbk', 'gb2312', 'gb18030', 'big5']
        for enc in encodings:
            try:
                with open(file_path, 'r', encoding=enc) as f:
                    content = f.read()
                return content
            except UnicodeDecodeError:
                continue
        raise UnicodeDecodeError("无法确定文件编码")


def count_lines(content):

    return len(content.splitlines())


def count_words(content):

    words = content.split()
    return len(words)


def count_characters(content):

    return len(content)


def count_specific_word(content, word):

    return content.lower().split().count(word.lower())


def display_stats(file_path, line_count, word_count, char_count, specific_word=None):
    print(f"\n文件 '{file_path}' 的统计结果：")
    print(f"行数: {line_count}")
    print(f"单词数: {word_count}")
    print(f"字符数: {char_count}")

    if specific_word:
        count = count_specific_word(open_file(file_path), specific_word)
        print(f"单词 '{specific_word}' 出现次数: {count}")


def main():
    print("=== 文件内容统计工具 ===")

    file_path = input("请输入文件路径：").strip()

    try:
        content = open_file(file_path)


        line_count = count_lines(content)
        word_count = count_words(content)
        char_count = count_characters(content)


        display_stats(file_path, line_count, word_count, char_count)


        specific_word = input("\n是否需要统计特定单词的出现次数？(输入单词或直接回车跳过): ").strip()
        if specific_word:
            display_stats(file_path, line_count, word_count, char_count, specific_word)

    except FileNotFoundError as e:
        print(f"错误: {e}")
    except UnicodeDecodeError as e:
        print(f"错误: {e}")
    except Exception as e:
        print(f"发生未知错误: {e}")


if __name__ == "__main__":
    main()